/**
 * 通用数据表格组件
 */
class DataTable {
    /**
     * 构造函数
     * @param {string} containerId 容器ID
     * @param {Array} columns 列配置
     * @param {Object} api API对象
     * @param {Function} rowFormatter 行格式化函数
     */
    constructor(containerId, columns, api, rowFormatter = null) {
        this.containerId = containerId;
        this.columns = columns;
        this.api = api;
        this.rowFormatter = rowFormatter;
        this.data = [];
        this.currentPage = 0;
        this.pageSize = 10;
        this.totalPages = 0;
        this.totalElements = 0;
        this.sortField = null;
        this.sortDirection = 'ASC';
        
        this.init();
    }
    
    /**
     * 初始化表格
     */
    init() {
        const container = document.getElementById(this.containerId);
        if (!container) {
            console.error(`容器 #${this.containerId} 不存在`);
            return;
        }
        
        // 创建表格结构
        container.innerHTML = `
            <div class="data-table-wrapper">
                <div class="data-table-header">
                    <div class="data-table-title">数据管理</div>
                    <div class="data-table-actions">
                        <button class="btn btn-primary" id="${this.containerId}-add-btn">新增</button>
                        <input type="text" class="search-input" id="${this.containerId}-search" placeholder="搜索...">
                    </div>
                </div>
                <table class="data-table" id="${this.containerId}-table">
                    <thead>
                        <tr>
                            ${this.columns.map(col => `<th data-field="${col.field}">${col.title}</th>`).join('')}
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <div class="data-table-pagination">
                    <button class="btn btn-sm" id="${this.containerId}-prev-btn">上一页</button>
                    <span class="pagination-info">第 <span id="${this.containerId}-current-page">1</span> 页，共 <span id="${this.containerId}-total-pages">1</span> 页</span>
                    <button class="btn btn-sm" id="${this.containerId}-next-btn">下一页</button>
                </div>
            </div>
            
            <!-- 编辑表单模态框 -->
            <div class="modal" id="${this.containerId}-modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 id="${this.containerId}-modal-title">编辑</h3>
                        <span class="close" id="${this.containerId}-modal-close">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="${this.containerId}-form">
                            ${this.columns.filter(col => !col.readonly).map(col => `
                                <div class="form-group">
                                    <label for="${this.containerId}-${col.field}">${col.title}</label>
                                    ${this.getInputByType(col)}
                                </div>
                            `).join('')}
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-secondary" id="${this.containerId}-modal-cancel">取消</button>
                        <button class="btn btn-primary" id="${this.containerId}-modal-save">保存</button>
                    </div>
                </div>
            </div>
        `;
        
        // 绑定事件
        this.bindEvents();
        
        // 加载数据
        this.loadData();
    }
    
    /**
     * 根据列类型获取表单输入元素
     * @param {Object} column 列配置
     * @returns {string} HTML字符串
     */
    getInputByType(column) {
        const id = `${this.containerId}-${column.field}`;
        
        switch (column.type) {
            case 'select':
                return `
                    <select id="${id}" name="${column.field}" class="form-control">
                        ${column.options.map(opt => `<option value="${opt.value}">${opt.label}</option>`).join('')}
                    </select>
                `;
            case 'textarea':
                return `<textarea id="${id}" name="${column.field}" class="form-control" rows="3"></textarea>`;
            case 'number':
                return `<input type="number" id="${id}" name="${column.field}" class="form-control">`;
            case 'date':
                return `<input type="date" id="${id}" name="${column.field}" class="form-control">`;
            case 'password':
                return `<input type="password" id="${id}" name="${column.field}" class="form-control">`;
            case 'checkbox':
                return `<input type="checkbox" id="${id}" name="${column.field}" class="form-check-input">`;
            case 'image':
                return `
                    <input type="file" id="${id}-file" name="${column.field}_file" class="form-control" accept="image/*">
                    <input type="hidden" id="${id}" name="${column.field}">
                    <div id="${id}-preview" class="image-preview"></div>
                `;
            default:
                return `<input type="text" id="${id}" name="${column.field}" class="form-control">`;
        }
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        const container = document.getElementById(this.containerId);
        
        // 表头排序
        const tableHeaders = container.querySelectorAll('th[data-field]');
        tableHeaders.forEach(th => {
            th.addEventListener('click', () => {
                const field = th.getAttribute('data-field');
                if (this.sortField === field) {
                    this.sortDirection = this.sortDirection === 'ASC' ? 'DESC' : 'ASC';
                } else {
                    this.sortField = field;
                    this.sortDirection = 'ASC';
                }
                this.loadData();
            });
        });
        
        // 分页按钮
        document.getElementById(`${this.containerId}-prev-btn`).addEventListener('click', () => {
            if (this.currentPage > 0) {
                this.currentPage--;
                this.loadData();
            }
        });
        
        document.getElementById(`${this.containerId}-next-btn`).addEventListener('click', () => {
            if (this.currentPage < this.totalPages - 1) {
                this.currentPage++;
                this.loadData();
            }
        });
        
        // 新增按钮
        document.getElementById(`${this.containerId}-add-btn`).addEventListener('click', () => {
            this.openModal();
        });
        
        // 搜索框
        const searchInput = document.getElementById(`${this.containerId}-search`);
        searchInput.addEventListener('input', this.debounce(() => {
            this.currentPage = 0;
            this.loadData(searchInput.value);
        }, 300));
        
        // 模态框关闭
        document.getElementById(`${this.containerId}-modal-close`).addEventListener('click', () => {
            this.closeModal();
        });
        
        document.getElementById(`${this.containerId}-modal-cancel`).addEventListener('click', () => {
            this.closeModal();
        });
        
        // 保存按钮
        document.getElementById(`${this.containerId}-modal-save`).addEventListener('click', () => {
            this.saveData();
        });
    }
    
    /**
     * 加载数据
     * @param {string} search 搜索关键词
     */
    async loadData(search = '') {
        try {
            const response = await this.api.getPage(
                this.currentPage,
                this.pageSize,
                this.sortField,
                this.sortDirection
            );
            
            if (response.success) {
                this.data = response.data.content;
                this.totalPages = response.data.totalPages;
                this.totalElements = response.data.totalElements;
                
                this.renderTable();
                this.updatePagination();
            } else {
                this.showMessage('加载数据失败: ' + response.message, 'error');
            }
        } catch (error) {
            this.showMessage('加载数据失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 渲染表格
     */
    renderTable() {
        const tbody = document.querySelector(`#${this.containerId}-table tbody`);
        tbody.innerHTML = '';
        
        if (this.data.length === 0) {
            const tr = document.createElement('tr');
            tr.innerHTML = `<td colspan="${this.columns.length + 1}" class="text-center">暂无数据</td>`;
            tbody.appendChild(tr);
            return;
        }
        
        this.data.forEach(item => {
            const tr = document.createElement('tr');
            
            // 使用自定义行格式化函数或默认格式化
            const rowData = this.rowFormatter ? this.rowFormatter(item) : item;
            
            // 渲染数据列
            this.columns.forEach(col => {
                const td = document.createElement('td');
                
                if (col.render) {
                    // 使用自定义渲染函数
                    td.innerHTML = col.render(rowData[col.field], rowData);
                } else {
                    // 默认渲染
                    td.textContent = rowData[col.field] || '';
                }
                
                tr.appendChild(td);
            });
            
            // 渲染操作列
            const actionTd = document.createElement('td');
            actionTd.className = 'actions';
            actionTd.innerHTML = `
                <button class="btn btn-sm btn-edit" data-id="${item.id}">编辑</button>
                <button class="btn btn-sm btn-delete" data-id="${item.id}">删除</button>
            `;
            tr.appendChild(actionTd);
            
            // 绑定行操作事件
            tr.querySelector('.btn-edit').addEventListener('click', () => {
                this.openModal(item);
            });
            
            tr.querySelector('.btn-delete').addEventListener('click', () => {
                this.confirmDelete(item);
            });
            
            tbody.appendChild(tr);
        });
    }
    
    /**
     * 更新分页信息
     */
    updatePagination() {
        document.getElementById(`${this.containerId}-current-page`).textContent = this.currentPage + 1;
        document.getElementById(`${this.containerId}-total-pages`).textContent = this.totalPages;
        
        // 禁用/启用分页按钮
        document.getElementById(`${this.containerId}-prev-btn`).disabled = this.currentPage === 0;
        document.getElementById(`${this.containerId}-next-btn`).disabled = this.currentPage >= this.totalPages - 1;
    }
    
    /**
     * 打开编辑模态框
     * @param {Object} item 要编辑的数据项，为空则为新增
     */
    openModal(item = null) {
        const modal = document.getElementById(`${this.containerId}-modal`);
        const modalTitle = document.getElementById(`${this.containerId}-modal-title`);
        
        // 设置模态框标题
        modalTitle.textContent = item ? '编辑' : '新增';
        
        // 清空表单
        const form = document.getElementById(`${this.containerId}-form`);
        form.reset();
        
        // 设置表单数据
        if (item) {
            this.columns.filter(col => !col.readonly).forEach(col => {
                const input = document.getElementById(`${this.containerId}-${col.field}`);
                if (!input) return;
                
                const value = item[col.field];
                
                switch (col.type) {
                    case 'checkbox':
                        input.checked = !!value;
                        break;
                    case 'image':
                        input.value = value || '';
                        const preview = document.getElementById(`${this.containerId}-${col.field}-preview`);
                        if (preview && value) {
                            preview.innerHTML = `<img src="${value}" alt="预览">`;
                        } else if (preview) {
                            preview.innerHTML = '';
                        }
                        break;
                    default:
                        input.value = value !== undefined && value !== null ? value : '';
                }
            });
            
            // 保存当前编辑项的ID
            form.dataset.id = item.id;
        } else {
            // 清除ID
            delete form.dataset.id;
        }
        
        // 显示模态框
        modal.style.display = 'block';
    }
    
    /**
     * 关闭编辑模态框
     */
    closeModal() {
        const modal = document.getElementById(`${this.containerId}-modal`);
        modal.style.display = 'none';
    }
    
    /**
     * 保存数据
     */
    async saveData() {
        try {
            const form = document.getElementById(`${this.containerId}-form`);
            const formData = {};
            
            // 收集表单数据
            this.columns.filter(col => !col.readonly).forEach(col => {
                const input = document.getElementById(`${this.containerId}-${col.field}`);
                if (!input) return;
                
                let value;
                switch (col.type) {
                    case 'checkbox':
                        value = input.checked;
                        break;
                    case 'number':
                        value = input.value ? parseFloat(input.value) : null;
                        break;
                    default:
                        value = input.value;
                }
                
                formData[col.field] = value;
            });
            
            // 处理文件上传
            const fileUploads = this.columns.filter(col => col.type === 'image');
            for (const col of fileUploads) {
                const fileInput = document.getElementById(`${this.containerId}-${col.field}-file`);
                if (fileInput && fileInput.files.length > 0) {
                    const file = fileInput.files[0];
                    // 这里可以实现文件上传逻辑，例如：
                    // const uploadResult = await this.uploadFile(file);
                    // formData[col.field] = uploadResult.url;
                }
            }
            
            let response;
            if (form.dataset.id) {
                // 更新
                response = await this.api.update(form.dataset.id, formData);
            } else {
                // 新增
                response = await this.api.create(formData);
            }
            
            if (response.success) {
                this.showMessage(form.dataset.id ? '更新成功' : '添加成功', 'success');
                this.closeModal();
                this.loadData();
            } else {
                this.showMessage(response.message || '操作失败', 'error');
            }
        } catch (error) {
            this.showMessage('操作失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 确认删除
     * @param {Object} item 要删除的数据项
     */
    confirmDelete(item) {
        if (confirm(`确定要删除这条数据吗？`)) {
            this.deleteData(item.id);
        }
    }
    
    /**
     * 删除数据
     * @param {string|number} id 数据ID
     */
    async deleteData(id) {
        try {
            const response = await this.api.delete(id);
            
            if (response.success) {
                this.showMessage('删除成功', 'success');
                this.loadData();
            } else {
                this.showMessage(response.message || '删除失败', 'error');
            }
        } catch (error) {
            this.showMessage('删除失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 显示消息提示
     * @param {string} message 消息内容
     * @param {string} type 消息类型：success, error, info
     */
    showMessage(message, type = 'info') {
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.textContent = message;
        
        // 添加到页面
        document.body.appendChild(messageEl);
        
        // 自动消失
        setTimeout(() => {
            messageEl.classList.add('message-hide');
            setTimeout(() => {
                document.body.removeChild(messageEl);
            }, 300);
        }, 3000);
    }
    
    /**
     * 防抖函数
     * @param {Function} func 要执行的函数
     * @param {number} wait 等待时间
     * @returns {Function} 防抖后的函数
     */
    debounce(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(context, args);
            }, wait);
        };
    }
}